package cn.t222.ch04;

import cn.t222.ch04.pojo.Book;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.UUID;

@SpringBootApplication
@RestController
@Slf4j
@ServletComponentScan
public class Ch04App {
    @Value("${upload.path}")
    private String path;
    public static void main(String[] args) {
        SpringApplication.run(Ch04App.class, args);
    }

    @CrossOrigin(value = "http://localhost:63342")
    @GetMapping("/books/{name}")
    public Book get(@PathVariable String name) {
        return new Book(1,name,"张三",new Date());
    }



    @PostMapping("/upload")
    public String upload(String desc, MultipartFile myfile, HttpServletRequest request) throws Exception {
//        String path = request.getServletContext().getRealPath("/");
        log.info("path:{}", path);
        String originalFilename = myfile.getOriginalFilename();
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("filename:{}", filename);
        myfile.transferTo(new File(path, filename));
        return "http://localhost:8080/" + filename;
    }
}
